﻿using Common;
using DadayunApi.Model;
using KbtSync.BLL;
using KbtSync.DAL;
using KbtSync.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace KbtSync
{
    public partial class MainForm : Form
    {
        AppAuthBase appAuth = null;
        string baseUri = "https://api.dadayun.cn";
        DadayunDAL ddyDal = null;
        string erpConnStr = null;
        string settingFile = "settings.ini";
        MyConfiguration cfg = new MyConfiguration(true);

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            appAuth = new AppAuthBase
            {
                AppKey = "c514ea09ccdd4435a636443c0331d438",
                AppSecret = "c7ea1d12c4dd456f9019c47ed638b4b3",
                Username = "ccjungle",
                Password = "tech8046",
                TenantName = "kenbotong",
                PublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuFXMJ+EEgSGCXSy5ORYAUX1yn3tCGC6xCvJACcyK9cwqc5Wglp2cAY7dqrXUH8AJD+kwSTFMxPWeusl6i8JuJB0bktSmgqBhhq979DbSotZqOWAjRUNzGeph/fTXUDIzZ8AvNZOCUcHbIZP//60QWCc7fsEDPRBgStpIgXA03KL63AWyMbU92sXe/rLN1nxAkgzRLOcL87NdQTNBpHYRIoIp1OP7chXzLOq+J4ZfNHhR7bLujIg8M0C42ZIjl52YV7m4D69ZzChDW+1/zWXHl35I8kOjvH+1rjlkaq1kKO5vJ4ROeHAhSJOjQ4Jjz5zfXKGiXg9F6yp7zpfvUzpuDQIDAQAB"
            };
            ddyDal = new DadayunDAL(appAuth, baseUri);
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder
            {
                DataSource = "192.16.4.22",
                InitialCatalog = "DB_KBT",
                UserID = "sa",
                Password = "kbt201182126631KBT",
                MultipleActiveResultSets = true,
                ApplicationName = "DDY Sync"
            };
            erpConnStr = builder.ConnectionString;
            if(File.Exists(settingFile))
            {
                cfg.Load(settingFile);
                RefreshConnections();
            }
        }
        BindingList<ProductReportResult> bPrdList = null;
        private void btnGet_Click(object sender, EventArgs e)
        {
            staInfo.Text = "正在获取产品清单...";
            var ilist = ddyDal.GetProductList();
            if(ilist!=null)
            {
                bPrdList = new BindingList<ProductReportResult>(ilist);
                dgvData.DataSource = null;
                dgvData.DataSource = bPrdList;
            }
            
            staInfo.Text = "获取产品清单完成!";
        }

        private void put_Click(object sender, EventArgs e)
        {
            List<Storage> storages = new List<Storage>
            {
                new Storage
                {
                    Warehouse = "产成品仓(一)",
                    StoreQty = 1000,
                    //LockToDate=DateTime.MaxValue
                },
                new Storage
                {
                    Warehouse="产成品仓(二)",
                    StoreQty=2000,
                    //LockToDate=DateTime.MaxValue
                }
            };

            StorageForm storageForm = new StorageForm
            {
                ErpItemCode = "11109005001",
                ProdName = "KBT30DP18-0809AT0,板状天线",
                Storages = storages
            };
            var ans= ddyDal.CreateStorageForm(storageForm);
            MessageBox.Show(ans.ToString());
        }

        private void btnChange_Click(object sender, EventArgs e)
        {
            List<FormInstanceInfo> forms = ddyDal.GetFormList("库存信息表", out int totalCount);
            if(forms.Count>0)
            {                
                StorageForm instance = ddyDal.GetStorageForm(forms[0].Id);
                if(instance.Storages.Count>0)
                {
                    instance.Storages[0].LockQty = 100;
                    //instance.Storages[0].LockToDate = DateTime.Now.AddDays(30);
                }
                instance.Storages.Add(new Storage
                {
                    Warehouse = "产成品仓(二)",
                    StoreQty = 3000,
                    //LockToDate = DateTime.MaxValue
                });
               var ans= ddyDal.EditStorageForm(forms[0].Id, instance);
                MessageBox.Show(ans.ToString());
            }
            
        }

        private void btnGetStorage_Click(object sender, EventArgs e)
        {
            if (bPrdList == null)
            {
                staInfo.Text = "获取产品库存失败: 产品清单为空!";
                return;
            }
            staInfo.Text = "正在获取产品库存...";
            SunlikeDAL slDal = new SunlikeDAL(erpConnStr);
            List<StorageResult> storageResults = new List<StorageResult>();
            
            foreach (var p in bPrdList)
            {
                var storageInfoes = slDal.GetStorageInfoes(p.ErpItemCode);
                if(storageInfoes!=null)
                {
                    foreach (var s in storageInfoes)
                    {
                        storageResults.Add(new StorageResult(p, s));
                    }
                }
                dgvData.DataSource = null;
                dgvData.DataSource = storageResults;
                Application.DoEvents();
            }
            staInfo.Text = "获取产品库存完成!";
        }

        private void btnSync_Click(object sender, EventArgs e)
        {
            MyLog.ClearLogs();
            int pageSize = Convert.ToInt16(txtPagesize.Text);
            staInfo.Text = "开始同步...";
            DdySyncBLL bLL = new DdySyncBLL(erpConnStr, baseUri, appAuth);
            //var ans = bLL.StorageSync1x1Mode(); //逐条处理模式
            /*
            var ans = bLL.StorageSyncBatchMode(out int count); //批量处理模式,更快更强!
            staInfo.Text = ans.ToString();*/
            //新批量处理模式, 控制每页数量,返回成功和失败数量
            DateTime now = DateTime.Now;
            IList<ProductReportResult> products= ddyDal.GetProductList();
#if DEBUG
            products = products.Take(pageSize).ToList(); //debug下只更新20条做测试
#endif
            int count = bLL.StorageSyncBatchMode(products, pageSize, out int errCount);
#if DEBUG
            MyLog.WriteInfo("批量写入json", bLL.WritingJson);
#endif
            TimeSpan ts = DateTime.Now - now;

            staInfo.Text = ", 本次更新了" + count + "个产品的库存,耗时+"+ts.TotalSeconds+"秒";
            staInfo.Text += "错误数量:" + errCount;
        }

        private void mnuSettings_Click(object sender, EventArgs e)
        {
            FrmSettings frm = new FrmSettings();
            if( frm.ShowDialog()==DialogResult.OK)
            {
                RefreshConnections();
               
            }
        }

        private void RefreshConnections()
        {
            if (File.Exists(settingFile))
            {
                cfg.Load(settingFile);

                if (cfg.ContainsKey(SettingItems.erpDbConnString))
                {
                     erpConnStr = cfg.ReadString(SettingItems.erpDbConnString);
                }
                appAuth = new AppAuthBase();
                
                if (cfg.ContainsKey(SettingItems.ddyBaseUri)) baseUri = cfg.ReadString(SettingItems.ddyBaseUri);
                if (cfg.ContainsKey(SettingItems.ddyTenantName)) appAuth.TenantName = cfg.ReadString(SettingItems.ddyTenantName);
                if (cfg.ContainsKey(SettingItems.ddyUsername)) appAuth.Username = cfg.ReadString(SettingItems.ddyUsername);
                if (cfg.ContainsKey(SettingItems.ddyPasswd)) appAuth.Password = cfg.ReadString(SettingItems.ddyPasswd);
                if (cfg.ContainsKey(SettingItems.ddyAppKey)) appAuth.AppKey = cfg.ReadString(SettingItems.ddyAppKey);
                if (cfg.ContainsKey(SettingItems.ddySecret)) appAuth.AppSecret = cfg.ReadString(SettingItems.ddySecret);
                if (cfg.ContainsKey(SettingItems.ddyPubkey)) appAuth.PublicKey = cfg.ReadString(SettingItems.ddyPubkey);
                ddyDal = new DadayunDAL(appAuth, baseUri);
            }
        }

        private void btnGetCrmStorages_Click(object sender, EventArgs e)
        {
            var ans = ddyDal.GetStorageReports("11984065001");
            dgvData.DataSource = null;
            dgvData.DataSource = ans;
        }
    }
   
}
